import Cookies from 'js-cookie'

var token = {
  savetoken: function(token) {
    Cookies.set('access_token', token.access_token)
    Cookies.set('enabled', token.enabled)
    Cookies.set('expires_in', token.expires_in)
    Cookies.set('refresh_token', token.refresh_token)
    Cookies.set('token_type', token.token_type)
    Cookies.set('scope', token.token_type)
  },
  deleteToken: function() {
    Cookies.remove('access_token')
    Cookies.remove('enabled')
    Cookies.remove('expires_in')
    Cookies.remove('refresh_token')
    Cookies.remove('token_type')
  },
  loadToken: function() {
    const tokenInfo = {}
    tokenInfo.access_token = Cookies.get('access_token')
    tokenInfo.enabled = Cookies.get('enabled')
    tokenInfo.expires_in = Cookies.get('expires_in')
    tokenInfo.refresh_token = Cookies.get('refresh_token')
    tokenInfo.token_type = Cookies.get('token_type')
    return tokenInfo
  },
  getTokenFromService: function(vue, code, callback, error) {
    vue.$ajax.post(vue.$config.accessTokenUri, {
      client_id: vue.$config.clientId,
      client_secret: vue.$config.client_secret,
      code: code,
      redirect_uri: vue.$config.redirect_uri,
      grant_type: vue.$config.grant_type
    }, {
      headers: { 'Accept': 'application/json', 'access-control-allow-origin': '*' }
    })
      .then(callback)
      .catch(error)
  }
}

export default token
